---
--- @File Name: demo
--- @Time     : 2023-09-05 19:21:51
--- @Docs     : 更为方便的请求库
require "import"
import "utils.easy"
local log = import "utils.logs"

local options = {
    fileName = "app.log",
    level = "INFO"
}

log:init("Spider", options)

local kox = {
    _URL = nil,
    _DATA = nil,
    SomeThing = {},
    _COOKIES = nil,
    _METHOD = "get",
    _ChARSET = nil,
    _HEADERS = {
        ["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.69"
    }
}

---设置请求地址
---@param fetchUrl string
---@return table
function kox:setUrl(fetchUrl)
    if self._URL == nil then
        self._URL = fetchUrl
    end
    return self
end

--- 增加请求头
---@param key string
---@param value string
function kox:setHeaders(key, value, ...)
    local op = { ... }

    self._HEADERS[string.lower(key)] = value

    if #op > 0 then
        for k, v in pairs(op) do
            self._HEADERS[string.lower(tostring(k))] = v
        end
    end

    return self
end

--- 设置请求模式
---@param method string
function kox:setMethod(method)
    self._METHOD = string.lower(method)
    return self
end

--- 增加参数
---@param data string
function kox:setData(data)
    self._DATA = data
    return self
end

--- 发送请求
---@param callBack function
function kox:send(callBack, errorBack)
    xpcall(function()
        if self._METHOD == "get" then
            Http.get(self._URL, self._COOKIES, self._ChARSET, self._HEADERS, callBack)
        elseif self._METHOD == "post" then
            Http.post(self._URL, self._DATA, self._COOKIES, self._ChARSET, self._HEADERS, callBack)
        end
    end, errorBack)
    return self
end

-- 默认传递参数
function kox.Err(err)
    --log:debug(err)
    print(err)
end

return kox
